﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Admin_Assignments_Essay : System.Web.UI.Page
{
    ILE_Global ileGlobal = new ILE_Global();
    ILE_Config ileConfig = new ILE_Config();

    //static string Mode = String.Empty;
    protected string Mode
    {
        get
        {
            return (string)ViewState["Mode"];
        }
        set
        {
            ViewState["Mode"] = value;
        }
    }
    protected int CourseID
    {
        get
        {
            return (int)ViewState["CourseID"];
        }
        set
        {
            ViewState["CourseID"] = value;
        }
    }

    protected int SectionNumber
    {
        get
        {
            return (int)ViewState["SectionNumber"];
        }
        set
        {
            ViewState["SectionNumber"] = value;
        }
    }

    protected int StandardID
    {
        get
        {
            return (int)ViewState["StandardID"];
        }
        set
        {
            ViewState["StandardID"] = value;
        }
    }

    AssignmentsBLL assignmentsLogic = new AssignmentsBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                Mode = Request.QueryString["Mode"];
            }
            catch { }

            GridViewCourses.Sort("Title", SortDirection.Ascending);

            if (Mode == "Create")
            {
                WizardCreateEssayAssignment.NavigationStyle.CssClass = "Hidden";
                PanelCreateEssayAssignment.Visible = true;
            }
            else if (Mode == "Edit")
            {
                WizardEditEssayAssignment.NavigationStyle.CssClass = "Hidden";
                PanelEditEssayAssignment.Visible = true;
            }
        }
    }

    protected void btnOpenCreateEssayAssignment_Click(object sender, EventArgs e)
    {
        ResetEssayAssignment("Create");
    }

    protected void btnOpenEditEssayAssignment_Click(object sender, EventArgs e)
    {
        ResetEssayAssignment("Edit");
    }

    private void ResetEssayAssignment(string Mode)
    {
        if (Mode == "Create")
        {
            Response.Redirect("Assignments_Essay.aspx?Mode=Create");
        }
        else if (Mode == "Edit")
        {
            Response.Redirect("Assignments_Essay.aspx?Mode=Edit");
        }
    }

    protected void GridViewCourses_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (((GridView)sender).SelectedIndex != -1)
        {
            WizardCreateEssayAssignment.NavigationStyle.CssClass = "";
            CourseID = Convert.ToInt32(((GridView)sender).SelectedValue.ToString());
            LoadSectionsByCourseID(false);
        }
        else
        {
            WizardCreateEssayAssignment.NavigationStyle.CssClass = "Hidden";
            PanelCreateEssaySections.Visible = false;
        }
    }

    protected void chkboxCreateEssaySectionsShowDisabled_CheckedChanged(object sender, EventArgs e)
    {
        LoadSectionsByCourseID(((CheckBox)sender).Checked);
    }

    protected void LoadSectionsByCourseID(bool showDisabled)
    {
        ClassBLL classLogic = new ClassBLL();

        lstboxSections.Items.Clear();

        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);

        foreach (Classes.Courses_SectionRow section in sections)
        {
            ListItem newItem = new ListItem(section.SectionNumber.ToString(), section.SectionNumber.ToString());
            if (showDisabled)
            {
                lstboxSections.Items.Add(newItem);
            }
            else
            {
                if (section.IsEnabled == true)
                    lstboxSections.Items.Add(newItem);
            }
        }

        PanelCreateEssaySections.Visible = true;
    }

    protected void WizardCreateEssayAssignment_ActiveStepChanged(object sender, EventArgs e)
    {
        if (WizardCreateEssayAssignment.ActiveStepIndex == 0)
        {
            // Hide Selected Sections when User comes back to this step
            lblCreateEssaySelectedSections.Text = "Selected Sections: ";
            lblCreateEssaySelectedSections.Visible = false;
        }
        else if (WizardCreateEssayAssignment.ActiveStepIndex == 1)
        {
            if (GridViewCourses.SelectedIndex == -1)
            {
                WizardCreateEssayAssignment.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "You must select a class to assign the essay to.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                return;
            }
            if (lstboxSections.SelectedIndex == -1)
            {
                WizardCreateEssayAssignment.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "At least 1 section must be selected from the 'Sections' Listbox.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            }
            else
            {
                StandardID = Convert.ToInt32(RadioButtonListStandardID.SelectedValue);
                txtGeneralStartDate.Text = DateTime.Now.ToString("MM/dd/yyyy");
                txtGeneralEndDate.Text = DateTime.Now.AddDays(1).ToString("MM/dd/yyyy");
            }

            ClassStandardsBLL classStandardsLogic = new ClassStandardsBLL();
            try
            {
                if (classStandardsLogic.GetClassStandard(CourseID, StandardID).IsStandardEnabled == false)
                {
                    WizardCreateEssayAssignment.ActiveStepIndex = 0;
                    // *SteveMsg
                    string _msg = "You have selected a standard that is disabled. Please make sure to enabled the standard using the \"Class Standard\" Page.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                }
            }
            catch
            {
                WizardCreateEssayAssignment.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "You have selected a standard that is disabled. Please make sure to enable the standard using the \"Class Standard\" Page.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            }

            ClassBLL classLogic = new ClassBLL();
            Classes.CoursesRow course = classLogic.GetCourse(CourseID);
            string Standard = String.Empty;
            switch (StandardID)
            {
                case 1:
                    Standard = "Getting Started";
                    break;
                case 2:
                    Standard = "Finding Sources";
                    break;
                case 3:
                    Standard = "Evaluating Sources";
                    break;
                case 4:
                    Standard = "Writing with Sources";
                    break;
            }
            txtCreateGeneralAssignmentName.Text = Standard + " Essay For " + course.Title;

            // Showing Selected Sections
            {
                foreach (ListItem item in lstboxSections.Items)
                {
                    if (item.Selected)
                        lblCreateEssaySelectedSections.Text += item.Value.ToString() + ", ";
                }

                lblCreateEssaySelectedSections.Text = lblCreateEssaySelectedSections.Text.Substring(0, lblCreateEssaySelectedSections.Text.Length - 2);
                lblCreateEssaySelectedSections.Visible = true;
            }

        }
    }

    protected void chkboxGeneralSendNotificationEmail_CheckedChanged(object sender, EventArgs e)
    {
        if (chkboxGeneralSendNotificationEmail.Checked)
            PanelGeneralSendNotificationEmailOption.Visible = true;
        else
            PanelGeneralSendNotificationEmailOption.Visible = false;
    }

    protected void WizardCreateEssayAssignment_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        string AssignmentName = txtCreateGeneralAssignmentName.Text;
        string AssignmentDirections = txtCreateGeneralDirections.Value;

        if (AssignmentName.Trim().Length <= 0)
        {
            // *SteveMsg
            string _msg = "Assignment Name is Required.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        if (txtGeneralStartDate.Text == String.Empty ||
            txtGeneralStartDateTime.Text == String.Empty ||
            txtGeneralEndDate.Text == String.Empty ||
            txtGeneralEndDateTime.Text == String.Empty)
        {
            // *SteveMsg
            string _msg = "Please Enter Start and End Date Times.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        if (chkboxGeneralSendNotificationEmail.Checked && txtGeneralSendNotificationEmailEssayEndHours.Text == String.Empty)
        {
            txtGeneralSendNotificationEmailEssayEndHours.Text = "24";
        }

        DateTime StartDateTime = new DateTime();
        DateTime EndDateTime = new DateTime();

        try
        {
            StartDateTime = Convert.ToDateTime(txtGeneralStartDate.Text + " " + txtGeneralStartDateTime.Text);
            EndDateTime = Convert.ToDateTime(txtGeneralEndDate.Text + " " + txtGeneralEndDateTime.Text);
        }
        catch
        {
            // *SteveMsg
            string _msg = "Please Enter Valid Start and End Date Times.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        int EndDateTimeHours = Convert.ToInt32(txtGeneralSendNotificationEmailEssayEndHours.Text);

        bool SendNotify = chkboxGeneralSendNotificationEmail.Checked;
        bool SendNotifyStart = false;
        bool SendNotifyEnd = false;

        if (SendNotify)
        {
            SendNotifyStart = chkboxGeneralSendNotificationEmailEssayStart.Checked;
            SendNotifyEnd = chkboxGeneralSendNotificationEmailEssayEnd.Checked;
        }

        int AssignmentID = assignmentsLogic.InsertAssignment("Essay", AssignmentName, AssignmentDirections, SendNotifyStart, SendNotifyEnd, EndDateTimeHours, false, StartDateTime, EndDateTime);

        bool result = AssignmentID != 0;
        if (result)
        {
            ScheduledEmailsToSendBLL autoemailLogic = new ScheduledEmailsToSendBLL();

            foreach (ListItem item in lstboxSections.Items)
            {
                if (item.Selected)
                {
                    int _sectionNumber = Convert.ToInt32(item.Value);
                    bool result2 = assignmentsLogic.InsertRelation(AssignmentID, CourseID, _sectionNumber, StandardID);
                    if (!result2)
                        result = false;

                    if (SendNotifyStart)
                    {
                        autoemailLogic.InsertScheduledEmailToSend(AssignmentID, "Starts", CourseID, _sectionNumber, StartDateTime);
                    }

                    if (SendNotifyEnd)
                    {
                        autoemailLogic.InsertScheduledEmailToSend(AssignmentID, "BeforeDue", CourseID, _sectionNumber, EndDateTime.AddHours(-EndDateTimeHours));
                    }
                }
            }
        }

        if (result)
        {
            // *SteveMsg
            string _message = "The Essay has been successfully assigned.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _message, 1, "Assignments_Essay.aspx");
        }
        else
        {
            // *SteveMsg
            string _message = "Failed to assign the Essay.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
        }
    }

    #region Edit Essay

    protected void WizardEditEssayAssignment_ActiveStepChanged(object sender, EventArgs e)
    {
        if (WizardEditEssayAssignment.ActiveStepIndex == 0)
        {
            // Hide Selected Sections when User comes back to this step
            lblEditEssaySelectedSections.Text = "Selected Sections: ";
            lblEditEssaySelectedSections.Visible = false;
        }
        else if (WizardEditEssayAssignment.ActiveStepIndex == 1)
        {
            if (GridViewEssayAssignments.SelectedIndex == -1)
            {
                WizardEditEssayAssignment.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "You must select an essay to edit.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                return;
            }
            if (lstboxEditSections.SelectedIndex == -1)
            {
                WizardEditEssayAssignment.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "At least 1 section must be selected from the 'Sections' Listbox.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            }
            else
            {
                StandardID = Convert.ToInt32(RadioButtonListEditStandardID.SelectedValue);
                int AssignmentID = Convert.ToInt32(GridViewEssayAssignments.SelectedValue);
                Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);
                txtEditGeneralAssignmentName.Text = assignment.AssignmentTitle;
                txtEditGeneralDirections.Value = assignment.Instruction;
                txtEditGeneralStartDate.Text = assignment.StartDateTime.ToString("d");
                txtEditGeneralStartDateTime.Text = assignment.StartDateTime.ToString("t");
                txtEditGeneralEndDate.Text = assignment.EndDateTime.ToString("d");
                txtEditGeneralEndDateTime.Text = assignment.EndDateTime.ToString("t");

                // Showing Selected Sections
                {
                    foreach (ListItem item in lstboxEditSections.Items)
                    {
                        if (item.Selected)
                            lblEditEssaySelectedSections.Text += item.Value.ToString() + ", ";
                    }

                    lblEditEssaySelectedSections.Text = lblEditEssaySelectedSections.Text.Substring(0, lblEditEssaySelectedSections.Text.Length - 2);
                    lblEditEssaySelectedSections.Visible = true;
                }
            }
        }
    }

    protected void GridViewEssayAssignments_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (((GridView)sender).SelectedIndex != -1)
        {
            int AssignmentID = Convert.ToInt32(((GridView)sender).SelectedValue);
            Assignments.RelationsDataTable relations = assignmentsLogic.GetRelationsByAssignmentID(AssignmentID);
            CourseID = relations[0].CourseID;
            int tempStandardID = relations[0].StandardID;
            ClassBLL classLogic = new ClassBLL();
            lblEditClass.Text = classLogic.GetCourse(CourseID).Title;

            FillLstboxEditSections(CourseID);

            foreach (ListItem item in lstboxEditSections.Items)
            {
                foreach (Assignments.RelationsRow relation in relations)
                {
                    if (item.Value == relation.SectionNumber.ToString())
                        item.Selected = true;
                }
            }

            foreach (ListItem item in RadioButtonListEditStandardID.Items)
            {
                if (item.Value == tempStandardID.ToString())
                {
                    item.Selected = true;
                    break;
                }
            }

            WizardEditEssayAssignment.NavigationStyle.CssClass = "";

            PanelEditEssaySections.Visible = true;
        }
        else
        {
            WizardEditEssayAssignment.NavigationStyle.CssClass = "Hidden";
        }
    }

    protected void FillLstboxEditSections(int CourseID)
    {
        lstboxEditSections.Items.Clear();
        ClassBLL classLogic = new ClassBLL();
        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);
        foreach (Classes.Courses_SectionRow section in sections)
        {
            lstboxEditSections.Items.Add(new ListItem(section.SectionNumber.ToString(), section.SectionNumber.ToString()));
        }
    }

    protected void chkboxEditGeneralSendNotificationEmail_CheckedChanged(object sender, EventArgs e)
    {

    }

    protected void WizardEditEssayAssignment_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        string AssignmentName = txtEditGeneralAssignmentName.Text;
        string AssignmentDirections = txtEditGeneralDirections.Value;

        if (AssignmentName.Trim().Length <= 0)
        {
            // *SteveMsg
            string _msg = "Assignment Name is Required.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        if (txtEditGeneralStartDate.Text == String.Empty ||
            txtEditGeneralStartDateTime.Text == String.Empty ||
            txtEditGeneralEndDate.Text == String.Empty ||
            txtEditGeneralEndDateTime.Text == String.Empty)
        {
            // *SteveMsg
            string _msg = "Please Enter Start and End Date Times.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        if (chkboxEditGeneralSendNotificationEmail.Checked &&
            txtEditGeneralSendNotificationEmailEssayEndHours.Text == String.Empty)
        {
            txtEditGeneralSendNotificationEmailEssayEndHours.Text = "24";
        }

        DateTime StartDateTime = new DateTime();
        DateTime EndDateTime = new DateTime();

        try
        {
            StartDateTime = Convert.ToDateTime(txtEditGeneralStartDate.Text + " " + txtEditGeneralStartDateTime.Text);
            EndDateTime = Convert.ToDateTime(txtEditGeneralEndDate.Text + " " + txtEditGeneralEndDateTime.Text);
        }
        catch
        {
            // *SteveMsg
            string _msg = "Please Enter Valid Start and End Date Times.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        int EndDateTimeHours = Convert.ToInt32(txtEditGeneralSendNotificationEmailEssayEndHours.Text);

        bool SendNotify = chkboxEditGeneralSendNotificationEmail.Checked;
        bool SendNotifyStart = false;
        bool SendNotifyEnd = false;

        if (SendNotify)
        {
            SendNotifyStart = chkboxGeneralSendNotificationEmailEssayStart.Checked;
            SendNotifyEnd = chkboxGeneralSendNotificationEmailEssayEnd.Checked;
        }

        int AssignmentID = Convert.ToInt32(GridViewEssayAssignments.SelectedValue);

        bool result = assignmentsLogic.UpdateAssignment("Essay", AssignmentName, AssignmentDirections, SendNotifyStart, SendNotifyEnd, EndDateTimeHours, false, StartDateTime, EndDateTime, AssignmentID);

        if (result)
        {
            assignmentsLogic.DeleteRelationsByAssignmentID(AssignmentID);
            foreach (ListItem item in lstboxEditSections.Items)
            {
                if (item.Selected)
                {
                    if (!assignmentsLogic.InsertRelation(AssignmentID, CourseID, Convert.ToInt32(item.Value), StandardID))
                        result = false;
                }
            }
        }

        if (result)
        {
            // *SteveMsg
            string _message = "The Essay has been successfully edited.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _message, 1, "Assignments_Essay.aspx");
        }
        else
        {
            // *SteveMsg
            string _message = "Failed to edit the Essay.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
        }
    }


    protected void btnEssayDelete_Click(object sender, EventArgs e)
    {
        AssignmentsBLL assignmentLogic = new AssignmentsBLL();
        int AssignmentID = Convert.ToInt32(GridViewEssayAssignments.SelectedValue);
        bool result = assignmentLogic.DeleteAssignment(AssignmentID);

        if (result)
        {
            // *SteveMsg
            string _message = "The essay assignment has been successfully deleted.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _message, 1, "Assignments_Essay.aspx");
        }
        else
        {
            // *SteveMsg
            string _message = "Failed to delete the essay assignment.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
        }
    }

    #endregion
    protected void GridViewEssayAssignments_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GridView grdview = (GridView)sender;
            grdview.Sort("AssignmentTitle", SortDirection.Ascending);
        }
    }

    protected void txtSections_TextChanged(object sender, EventArgs e)
    {
        ConvertTextToSelectedListItem(((TextBox)sender).Text, lstboxSections);
    }

    protected void txtEditSections_TextChanged(object sender, EventArgs e)
    {
        ConvertTextToSelectedListItem(((TextBox)sender).Text, lstboxEditSections);
    }

    protected void ConvertTextToSelectedListItem(string text, ListBox listbox)
    {
        string original = text;
        string formatted = String.Empty;
        bool isContinuous = false;
        int[] sections = new int[60];
        int i = 0, j = 0, k = 0;

        listbox.SelectedIndex = -1;

        foreach (char ch in original)
        {
            if (ch >= '0' && ch <= '9')
            {
                formatted += ch;
            }
            else if (ch == ',')
            {
                try
                {
                    sections[i++] = Convert.ToInt32(formatted);
                }
                catch
                {
                    ModalPopupMessage.ShowModalPopup("ILE Message", "Text is not in format.", 2);
                    break;
                }

                if (isContinuous)
                {
                    k = i;
                    for (j = sections[i - 2] + 1; j < sections[i - 1]; j++)
                    {
                        sections[k++] = j;
                    }
                    i = k;
                    isContinuous = false;
                }

                formatted = String.Empty;
            }
            else if (ch == '-')
            {
                try
                {
                    sections[i++] = Convert.ToInt32(formatted);
                }
                catch
                {
                    ModalPopupMessage.ShowModalPopup("ILE Message", "Text is not in format.", 2);
                    break;
                }
                isContinuous = true;
                formatted = String.Empty;
            }
            else if (ch == ' ')
            {

            }
            else
            {
                ModalPopupMessage.ShowModalPopup("ILE Message", "Only numbers, ',', and '-' are allowed.", 2);
                break;
            }
        }

        try
        {
            sections[i++] = Convert.ToInt32(formatted);

            if (isContinuous)
            {
                k = i;
                for (j = sections[i - 2] + 1; j < sections[i - 1]; j++)
                {
                    sections[k++] = j;
                }
                isContinuous = false;
            }
        }
        catch
        {
        }

        foreach (int section in sections)
        {
            if (section == 0)
                break;

            ListItem item = new ListItem();
            try
            {
                item = listbox.Items.FindByValue(section.ToString());
                if (item.Selected)
                    ModalPopupMessage.ShowModalPopup("ILE Message", "Warning: Duplicate Sections.", 0);
                else
                    item.Selected = true;
            }
            catch
            {
                ModalPopupMessage.ShowModalPopup("ILE Message", "You have entered section number that does not exist. Sect." + section.ToString(), 2);
                break;
            }
        }
    }
}
